package com.hamster.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.hamster.entity.Bank;
import com.hamster.service.BankRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by opabinia on 2017/5/15.
 */
@RestController
@RequestMapping("/bank")
public class BankController {
    private String uri = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=%s&cardBinCheck=true";
    @Autowired
    private BankRepository bankRepository;

    @RequestMapping("/query/{cardNo}")
    public Map<String, Object> query(@PathVariable String cardNo) {
        RestTemplate restTemplate = new RestTemplate();
        // 只是测试
        Map result = new HashMap();
        ResponseEntity<Map> resp = restTemplate.getForEntity(String.format(uri, cardNo), Map.class);
        final String SUCCESS = "success";
        if (resp.getStatusCode() == HttpStatus.OK) {
            Map data = new HashMap();
            Map map = resp.getBody();
            String bankName = (String) map.get("bank");
            Bank bank = bankRepository.findByBank(bankName);
            if (bank != null) {
                data.put("bank", map.get("bank"));
                data.put("name", bank.getName());
                data.put("logo", bank.getLogo());
                result.put("result", ImmutableMap.of("data", data, SUCCESS, true));
            }
        } else {
            result.put("result", ImmutableMap.of(SUCCESS, false));
        }

        return result;
    }
}
